import { reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMutation } from '@tanstack/vue-query'

import { useUserStore } from '@/stores/user'
import { userMessage } from '@/apis/user/message'
import { invalidateQueries } from '@/apis/client'
import { ApiLogin, KeyApiGetUserInfo } from '@/apis/user'
import { parseRollbackLocation } from '@/router/redirect-login'
import { useFetchMessage } from '@/composables/useFetchMessage'

export function useLogin() {
  const formState = reactive({
    username: '',
    password: ''
  })

  const route = useRoute()
  const router = useRouter()
  const { login } = useUserStore()
  const { showMessage } = useFetchMessage([userMessage])

  const { mutate, isPending } = useMutation({
    mutationFn: ApiLogin,
    onSettled(data, error) {
      showMessage(data?.code ?? error?.data?.code)
    },
    async onSuccess({ data: { accessToken, refreshToken } }) {
      invalidateQueries(KeyApiGetUserInfo)
      if (await login(accessToken, refreshToken)) {
        await router.push(parseRollbackLocation(route))
      }
    }
  })

  const handleLogin = () => mutate(formState)

  return {
    formState,
    isPending,
    handleLogin
  }
}
